/**
 *
 */
package com.ireadbooks.service;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

/**
 * @author wut
 *
 */
@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.applicationContext = applicationContext;

    }

    public static void publishEvent(ApplicationEvent event) {
        //applicationContext.publishEvent(event);
        getApplicationContext().publishEvent(event);
    }


    private static ApplicationContext getApplicationContext() { //只取父类的applicationContext
        ApplicationContext c = applicationContext;
        ApplicationContext nextc = null;
        while (c != null) {
            nextc = c.getParent();
            if (nextc == null) {
                return c;
            } else {
                c = nextc;
            }
        }
        return c;
    }
}
